package comunity;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;

public class Community {
	private static Community c = null;
	public static final String broadcastWildcard = "broadcast";
	private HashMap<String, User> users;
	private HashMap<String, LinkedList<String>> conversations;

	private Community() {
		this.users = new HashMap<String, User>();
		this.conversations = new HashMap<String, LinkedList<String>>();
	}

	public boolean contains(User user) {
		synchronized (this) {
			return users.containsKey(user.getUsername());
		}
	}
	
	public int size(){
		synchronized (this) {
			return this.users.size();
		}
	}

	public Status getUserStatus(String username){
		synchronized (this) {
			User user = users.get(username);
			return user.getStatus();
		}
	}
	
	public GPSLocation getUserGPSLocation(String username){
		synchronized (this) {
			User user = users.get(username);
			return user.getGPSLocation();
		}
	}

	public void setUserStatus(String username, Status status){
		synchronized (this) {
			User user = users.get(username);
			user.setStatus(status);
			users.put(username, user);
		}
	}

	public void addUser(User user) {
		synchronized (this) {
			this.users.put(user.getUsername(), user);
			
			LinkedList<String> conversation = new LinkedList<String>();
			this.conversations.put(user.getUsername(), conversation);
		}
	}
	
	public void addMessageFrom(String username, String text) {
		synchronized (this) {
			LinkedList<String> messages = this.conversations.get(username);
			messages.addLast(text);
			this.conversations.put(username, messages);
		}
	}

	public LinkedList<String> getMessagesFrom(String username){
		synchronized (this) {
			return this.conversations.get(username);
		}
	}
	
	public void flushConversationFrom(String username){
		synchronized (this) {
			this.conversations.put(username, new LinkedList<String>());
		}
	}
	
	public Collection<String> getUsers(){
		synchronized (this) {
			Collection<String> users = new LinkedList<String>();
			for (User userInfo : this.users.values()) {
				users.add(userInfo.getUsername());
			}
			return users;
		}
	}
	
	public Collection<String> getOnlineUsers(){
		synchronized (this) {
			Collection<String> onlineUsers = new LinkedList<String>();
			for (User userInfo : this.users.values()) {
				if(userInfo.getStatus() == Status.OFFLINE)
					continue;
				onlineUsers.add(userInfo.getUsername());
			}
			return onlineUsers;
		}		
	}
	
	public synchronized static Community obtainCommunity() {
			if (c == null)
				c = new Community();
			System.out.print("C:: ");
			for(User user: c.users.values()){
				System.out.print(user.getUsername()+" "+user.getStatus().toString());
			}
			System.out.println();
			return c;
	}
}
